package com.losdun.aftersales.manager;

import com.losdun.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @Description
 * @Author Sword.Ye
 * @Date 2025/9/23
 **/
@Component
public class NumberGenerator {

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyMMdd");
    public static final String DECIMAL_FORMAT_PATTERN = "000";

    @Autowired
    private RedisCache redisCache;


    /**
     * 获取每日的递增id
     *
     * @param keyPrefix key前缀
     * @return
     */
    public String generateNo(String keyPrefix) {
        String formatDate = getCurrentDate();
        long incr = redisCache.incr(keyPrefix + formatDate, 1);
        if (incr == 1) {
            //设置超时时间为一天
            redisCache.expire(keyPrefix + formatDate, 24 * 60 * 60);
        }
        return createId(keyPrefix, formatDate, incr, DECIMAL_FORMAT_PATTERN);
    }

    private String createId(String keyPrefix, String formatDate, long incr, String formatPattern) {
        DecimalFormat df = new DecimalFormat(formatPattern);
        String format = df.format(incr);
        return keyPrefix + formatDate + format;
    }

    /**
     * 获取当前日期字符串
     */
    private String getCurrentDate() {
        return LocalDate.now().format(DATE_FORMATTER);
    }

}
